

import styled from 'styled-components';
import React, { CSSProperties, FC, useCallback, useEffect, useState } from 'react';
import { Flex, Tag, Typography, Input, Divider, Button, Table, Space, Tabs, Spin } from 'antd';
import {
    FacebookOutlined,
    LinkedinOutlined,
    TwitterOutlined,
    BarsOutlined,
    YoutubeOutlined,
} from '@ant-design/icons';
import { MetaDataObjectProperty } from '@/services';
import type { TabsProps } from 'antd';
import { dsBatchInsert, promptGenerateWithBuildin } from '@/services/local';
const { Paragraph, Title } = Typography;
const { TextArea } = Input;

import AdvancedPromptInput from '@/components/app/configuration/config-prompt/advanced-prompt-input';
import { PromptRole } from '@/models/debug';
import { SimpleEditor } from '@/components/editor';
import { CLASS_ATTRIBUTE_CLASS_IDENTIFIER, CLASS_CLASS_IDENTIFIER } from '@/services/constants';
import { uuid } from '@/utils';

export interface GenerateClassPromptInputProps {
    style?: CSSProperties;
    domainIdentifier: string;
    onCompleted?: () => void | Promise<void>
}

const ITEMS = [
    {
        title: '任务调度',
        icon: <BarsOutlined />,
        instruction: '任务调度系统,可以实现任务的管理、调度、监控等。'
    },
    {
        title: '用户管理',
        icon: <BarsOutlined />,
        instruction: '一个可以实现用户的注册、登录、用户维护、用户角色维护、角色权限维护的用户管理子系统。'
    },
    {
        title: '日志分析',
        icon: <BarsOutlined />,
        instruction: '实现系统中所有模块的日志记录、查询、统计。'
    },
    {
        title: '设备监控',
        icon: <BarsOutlined />,
        instruction: '一个以设备管理为基础数据，对设备进行CPU、内存等状态的监控，并能够对监控的信息进行告警、统计等的子系统。'
    }
];

export const GenerateClassPromptInput: FC<GenerateClassPromptInputProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [objects, setObjects] = useState<any[]>([]);

    const [relations, setRelations] = useState<any[]>([]);

    const [instruction, setInstruction] = useState<string>('');

    const [output, setOutput] = useState<string>('');

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
        },
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
        },
        {
            title: '主键',
            key: 'is_key',
            dataIndex: 'is_key',
            render: (text, record, index) => {
                return record.is_key ? '是' : '否';
            }
        },
        {
            title: '数据类型',
            key: 'data_type',
            dataIndex: 'data_type',
            valueType: 'text'
        },
        {
            title: '默认值',
            key: 'default_value',
            dataIndex: 'default_value',
            valueType: 'text'
        },
        {
            title: '是否是数字',
            key: 'is_number',
            dataIndex: 'is_number',
            render: (text, record, index) => {
                return record.is_key ? '是' : '否';
            }
        },
    ];

    useEffect(() => {
        if (!output || output.trim() === '') {
            setObjects([]);
            setRelations([]);
            return;
        }
        //
        try {
            let objectStr = output.replaceAll("```json", "").replaceAll("```", "");
            let objects = JSON.parse(objectStr);
            setObjects(objects.objects);
            setRelations(objects.relations);
        } catch (err) {

        }
    }, [output]);

    return (
        <Container style={props.style}>
            <Box style={{
                width: '300px',
                alignItems: 'flex-start',
                justifyContent: "flex-start"
            }}>
                <Paragraph ellipsis={false}>
                    AI生成器，根据用户输入的相关信息，自动生成对象以及属性等信息，点击应用可以直接录入到系统中。
                </Paragraph>
                <div>试一试</div>
                <Flex gap="4px 0" wrap>
                    {
                        ITEMS && ITEMS.map((item, index) => {
                            return <Tag key={`tag_${index}`} icon={item.icon || <BarsOutlined />} onClick={() => {
                                setInstruction(item.instruction);
                            }}>
                                {item.title}
                            </Tag>
                        })
                    }
                </Flex>
                <Divider></Divider>
                <TextArea rows={8} value={instruction} placeholder='写下清晰具体的说明' onChange={(event) => {
                    setInstruction(event.target.value);
                }}></TextArea>
                <ButtonContainer>
                    <Button style={{
                        width: '90px'
                    }} loading={loading} type={'primary'} onClick={async () => {
                        //
                        try {
                            setLoading(true);
                            const { error, ...res } = await promptGenerateWithBuildin('code-class', instruction, { model_config: 'gpt-4o-mini', no_variable: true })
                            console.log('----', res);
                            if (res && res.prompt) {
                                setOutput(res.prompt.replaceAll("```json", "").replaceAll("```", ""))
                            }
                            setLoading(false);
                        } catch (err) {
                            console.log(err);
                            setLoading(false);
                        }
                    }}>生成</Button>
                </ButtonContainer>
            </Box>
            <Divider style={{
                height: '100%'
            }} type={'vertical'}></Divider>
            <Box style={{
                flex: 1,
                marginLeft: '2px'
            }}>
                {
                    loading && <Spin></Spin>
                }
                {
                    !loading && (!output || output.trim() === '') && <>左侧进行生成</>
                }
                {
                    !loading && output && output.trim() !== '' && <Tabs
                        defaultActiveKey="1"
                        style={{
                            width: '100%',
                            height: '100%'
                        }}
                        tabBarExtraContent={<Button danger type={'primary'} size={'small'} loading={loading} onClick={async () => {
                            // 应用
                            try {
                                setLoading(true);
                                //objects
                                let objectInsert = [];
                                let attributeInsert = [];
                                for (let i = 0; i < objects.length; i++) {
                                    //插入
                                    let class_identifier = uuid();

                                    objectInsert.push([CLASS_CLASS_IDENTIFIER, {
                                        ...objects[i],
                                        identifier: class_identifier,
                                        domain_identifier: props.domainIdentifier
                                    }]);
                                    for (let j = 0; j < objects[i].attributes.length; j++) {
                                        //插入
                                        let attribute_identifier = uuid();
                                        attributeInsert.push([CLASS_ATTRIBUTE_CLASS_IDENTIFIER, {
                                            ...objects[i].attributes[j],
                                            identifier: attribute_identifier,
                                            class_identifier: class_identifier,
                                        }]);
                                    }
                                }
                                console.log(objectInsert, attributeInsert);
                                let res = await dsBatchInsert(0, objectInsert.concat(attributeInsert));
                                console.log(res);
                                setLoading(false);
                            } catch (err) {
                                setLoading(false);
                                console.log(err);
                            }
                        }}>应用</Button>}
                        items={[
                            {
                                key: '1',
                                label: '对象列表',
                                children: <>
                                    <Tabs key={`objects`} items={objects.map((item, index) => {
                                        return {
                                            key: `_${item.name}`,
                                            label: item.title,
                                            children: <Table
                                                key={'table_' + index}
                                                bordered
                                                loading={loading}
                                                rowKey={'identifier'}
                                                pagination={false}
                                                dataSource={item.attributes}
                                                columns={columns} />,
                                        };
                                    })} onChange={(key: string) => {

                                    }} />
                                </>,
                            }, {
                                key: '2',
                                label: '原始输出',
                                children:
                                    <EditorContainer>
                                        <SimpleEditor initValue={output} language='json' value={output} onChange={async (value) => {
                                            setOutput(value);
                                        }}></SimpleEditor>
                                    </EditorContainer>,
                            }
                        ]} />
                }
            </Box>
        </Container >
    );
}

export default GenerateClassPromptInput;

const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: row;
`;

const Box = styled.div`
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
`;

const ButtonContainer = styled.div`
    width: 100%;
    display: flex;
    height: 40px;
    justify-content: flex-end;
    align-items: center;
`;

const EditorContainer = styled.div`
    height: 100%;
    width: 100%;
`;